#pragma once

#include "Socket.hpp"

using namespace SocketModule;

class TcpClient
{
public:
    TcpClient(std::string server_ip, uint16_t port)
        : _server_ip(server_ip), _port(port), _sockfd(std::make_shared<TcpSocket>())
    {
        // 简单的断线重连
        int cnt = 5;
        while (cnt)
        {
            if (_sockfd->BuildClientSocket(_server_ip, _port))
            {
                break;
            }

            LOG(INFO, "连接失败，正在重连，重连剩余次数为: %d\n", cnt--);
            sleep(1); // 网络恢复的时间
        }

        if (cnt == 0)
        {
            LOG(INFO, "connect failed\n");
            exit(CONN_ERROR);
        }
        LOG(INFO, "connect success\n");
    }

    ~TcpClient()
    {
    }

    void Loop()
    {
        while (true)
        {
            std::string msg;
            std::cout << "[please enter] # ";
            std::getline(std::cin, msg);

            _sockfd->Send(msg);

            std::string echo_str;
            _sockfd->Recv(&echo_str);
            std::cout << echo_str << std::endl;
        }
    }

private:
    std::string _server_ip;
    uint16_t _port;
    SockSPtr _sockfd;
};